﻿using Cyss.Core;
using Cyss.Core.Helper;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace Cyss.Core.Api
{
    public class CustomExceptionFilterAttribute: ExceptionFilterAttribute
    {
        public CustomExceptionFilterAttribute()
        {
        }
        /// <summary>
        /// 发生异常时 进入
        /// </summary>
        /// <param name="context"></param>
        public override void OnException(ExceptionContext context)
        {
           
            if(context.RouteData!=null && context.RouteData.Values!=null && context.RouteData.Values.ContainsKey("action"))
            {
                LogHelper.WriteTextLog(context.Exception.ToString(),context.RouteData.Values["action"].ToString(), "CustomExceptionFilter");
            }
            else
            {          
                LogHelper.WriteTextLog(context.Exception.ToString(), "OnException", "CustomExceptionFilter");
            }

            if (!context.ExceptionHandled)        //异常未被处理
            {
                OperateResult ajaxRequstModel = new OperateResult();
                ajaxRequstModel.IsSuccess = false;
                ajaxRequstModel.Message = context.Exception.Message;
                context.Result = new JsonResult(ajaxRequstModel); ;

                

                context.ExceptionHandled = true;//异常已被处理
            }
        }
    }
}
